package com.mdnote.jianzhi_offer.array;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/11/6 17:43
 * @Email rhythm_2019@163.com
 * @Description 面试题20 表达数值的字符串
 */
public class Offer20 {
    private int index = 0;

    public boolean isNumber(String s) {
        // 数字： +/-[A.B]EeC
        if (s == null) {
            return false;
        }
        s = s.trim();
        if (s.length() == 0) {
            return false;
        }

        boolean flag = scanIntNum(s, 0);

        if (this.index < s.length() && s.charAt(this.index) == '.') {
            this.index = this.index + 1;
            flag = scanUnsignNum(s, this.index) || flag;
        }
        if (this.index < s.length() && (s.charAt(this.index) == 'e' || s.charAt(this.index) == 'E')) {
            this.index = this.index + 1;
            flag = scanIntNum(s, this.index) && flag;
        }


        return flag && this.index == s.length();
    }

    private boolean scanUnsignNum(String s, int start) {
        int tmp = start;
        while (tmp < s.length() && (s.charAt(tmp) >= '0' && s.charAt(tmp) <= '9')) {
            tmp++;
        }
        this.index = tmp;
        return tmp > start;
    }

    private boolean scanIntNum(String s, int start) {
        if (start >= s.length()) {
            return false;
        }
        if (s.charAt(start) == '+' || s.charAt(start) == '-') {
            return scanUnsignNum(s, start + 1);
        }
        return scanUnsignNum(s, start);
    }

    public static void main(String[] args) {
        Offer20 offer20 = new Offer20();
        System.out.println(offer20.isNumber("123"));
        System.out.println(offer20.isNumber("123.11"));
        System.out.println(offer20.isNumber("+123.11"));
        System.out.println(offer20.isNumber("+123.11e"));
        System.out.println(offer20.isNumber("+.11e"));
        System.out.println(offer20.isNumber(".11"));
        System.out.println(offer20.isNumber("+.1 1"));
        System.out.println(offer20.isNumber(" +.11"));
        System.out.println(offer20.isNumber(""));
        System.out.println(offer20.isNumber(". 1"));
        System.out.println(offer20.isNumber("1 4"));
        System.out.println(offer20.isNumber("11.11E-2"));
        System.out.println(offer20.isNumber("11E-2"));
//        System.out.println(offer20.isNumber("+123.11e11"));
    }
}
